// This file is required by the index.html file and will
// be executed in the renderer process for that window.
// No Node.js APIs are available in this process because
// `nodeIntegration` is turned off. Use `preload.js` to
// selectively enable features needed in the rendering
// process.

function btnGroup (){
  let html =
    '<a href="#!" class="btn btn-xs btn-primary m-r-5 edit-btn" title="修改" data-toggle="tooltip"><i class="mdi mdi-cloud-download"></i></a>' +
    '<a href="#!" class="btn btn-xs btn-danger m-r-5 del-btn" title="删除" data-toggle="tooltip"><i class="mdi mdi-delete-circle"></i></a>';
  return html;
}

const AccountTableOption = {
  classes: 'table table-bordered table-hover table-striped fix-table',
  dataType : 'json',        // 因为本示例中是跨域的调用,所以涉及到ajax都采用jsonp,
  uniqueId: 'email',
  idField: 'email',             // 每行的唯一标识字段
  toolbar: '#toolbar',       // 工具按钮容器
  showColumns: false,         // 是否显示所有的列
  showRefresh: true,         // 是否显示刷新按钮
  pagination: true,                    // 是否显示分页
  sortOrder: "asc",                    // 排序方式                                  // 传递参数
  sidePagination: "client",            // 分页方式：client客户端分页，server服务端分页
  pageNumber: 1,                       // 初始化加载第一页，默认第一页
  pageSize: 7,                        // 每页的记录行数
  pageList: [7],         // 可供选择的每页的行数
  search: true,                      // 是否显示表格搜索，此搜索是客户端搜索
  columns: [// 是否排序 
  { field: 'name', title: '发件人姓名', sortable: true },
  { field: 'email', title: '邮箱地址', sortable: true }, 
  { field: 'password2', title: '访问密码' },
  { field: 'operate', title: '操作', formatter: btnGroup,  // 自定义方法
      events: {
        'click .edit-btn': function (event, value, row, index) {
          if( row.email !== '') account_edit( row, index )
        },
        'click .del-btn': function (event, value, row, index) {
          if( row.email !== '') account_del( row, index )
        }
      }
  }],
  onLoadSuccess: function(data){
      $("[data-toggle='tooltip']").tooltip();
  }
}

$('#account_table').bootstrapTable(AccountTableOption);
$('#account_table').bootstrapTable('load', store.get('v1.accounts'))

$("#add_account_btn").click(function(){
  $.confirm({
    title: '新增发件人账号信息',
    content: `<form action="" class="formName">
      <div class="form-group">
        <label>姓名:</label>
        <input type="text" placeholder="姓名" class="name form-control" required />
      </div>
      <div class="form-group">
        <label>邮箱地址</label>
        <input type="email" placeholder="邮箱地址" class="email form-control" required />
      </div>
      <div class="form-group">
        <label>访问密码</label>
        <input type="text" placeholder="访问密码" class="password form-control" required />
      </div>
    </form>`,
    buttons: {
      formSubmit: {
          text: '提交',
          btnClass: 'btn-blue',
          action: function () {
            const name = this.$content.find('.name').val();
            const email = this.$content.find('.email').val();
            const password = this.$content.find('.password').val();
            if(!name || !email || !password){
                $.alert('请您输入完整！');
                return false;
            }
            const accounts = store.get('v1.accounts') || []
            let findIt = false
            accounts.forEach( item=>{
              if(item.email === email ) findIt = true
            })
            if( findIt ) {
              $.alert('Email已存在！');
            } else {
              accounts.push({name, email, password, password2: '******'})
              store.set('v1.accounts', accounts)
              $('#account_table').bootstrapTable('prepend', {name, email, password, password2: '******'});
              refrushAccountList()
            }
          }
      },
      cancel: {
          text: '取消'
      },
    },
    onContentReady: function () {
        var jc = this;
        this.$content.find('form').on('submit', function (e) {
            e.preventDefault();
            jc.$$formSubmit.trigger('click');
        });
    }
  });
})

function account_edit(row, index){
  const {name, email} = row
  $.confirm({
    title: '新增发件人账号信息',
    content: `<form action="" class="formName">
      <div class="form-group">
        <label>姓名:</label>
        <input type="text" placeholder="姓名" class="name form-control" required value="${name}"/>
      </div>
      <div class="form-group">
        <label>邮箱地址</label>
        <input type="email" placeholder="邮箱地址" class="email form-control" required value="${email}"/>
      </div>
      <div class="form-group">
        <label>访问密码</label>
        <input type="text" placeholder="访问密码" class="password form-control" required />
      </div>
    </form>`,
    buttons: {
      formSubmit: {
          text: '提交',
          btnClass: 'btn-blue',
          action: function () {
            const new_name = this.$content.find('.name').val();
            const new_email = this.$content.find('.email').val();
            const password = this.$content.find('.password').val();
            if(!new_name || !new_email || !password){
                $.alert('请您输入完整！');
                return false;
            }
            const accounts = store.get('v1.accounts')
            let findIt = false
            accounts.forEach( item=>{
              if(item.email === new_email && new_email !== email) findIt = true
            })
            if(findIt) {
              $.alert('该邮箱地址已存在，不允许重复!')
            } else {
              const newAccount = []
              accounts.forEach( item=>{
                if(item.name === name && item.email === email) {
                  item.name = new_name
                  item.email = new_email
                  item.password = password
                }
                newAccount.push(item)
              })
              store.set('v1.accounts', newAccount)
              $('#account_table').bootstrapTable('updateRow', {index: index, row: {name: new_name, email: new_email, password2: '******'}});
              refrushAccountList()
            }
          }
      },
      cancel: {
          text: '取消'
      },
    },
    onContentReady: function () {
        var jc = this;
        this.$content.find('form').on('submit', function (e) {
            e.preventDefault();
            jc.$$formSubmit.trigger('click');
        });
    }
  });
}

function account_del(row, index) {
  $.confirm({
    title: '提示',
    content: `你是否确认删除『${row.email}』的账号?`,
    type: 'green',
    buttons: {
      omg: {
          text: '确定',
          btnClass: 'btn-green',
          action: function(){
            let accounts = store.get('v1.accounts')
            const newArr = accounts.filter( item=>{
              return (item.name !== row.name && item.emal !== row.email) 
            })
            store.set('v1.accounts', newArr)
            $('#account_table').bootstrapTable('removeByUniqueId', row.email)
            refrushAccountList()
          }
      },
      close: {
          text: '取消',
      }
    }
  })
}
